package com.monkey.luffer.springboot.demo.basis.kcc.s3cmd;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import org.apache.commons.lang3.time.DateUtils;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author jiahong.liu
 */
public class GetObjects implements S3Oper {

	@Override
	public void request(AmazonS3 s3, MyCmd cmd) {
		if (cmd.getPrefix() == null) {
			System.out.println("下载时，-p 参数必输");
			return;
		}
		String[] prefix = cmd.getPrefix().split("-");
		if (prefix.length == 2) {
			getObjects(s3, cmd, prefix[0], prefix[1]);
		} else{
			getObjects(s3, cmd, cmd.getPrefix(), cmd.getPrefix());
		}

	}

	private void getObjects(AmazonS3 s3, MyCmd cmd, String begin, String end) {
		do {
			ListObjectsV2Result result = s3.listObjectsV2(cmd.getBucket(), begin);
			String[] arr = cmd.getBucket().split("-");
			String env = arr[arr.length - 1];
			if(result.getObjectSummaries().size()>0){
				File dstDir = new File(cmd.getDstPath() + "/" + env);
				if (dstDir.exists() && !dstDir.isDirectory()) {
					System.out.println("dstPath must be a path");
					return;
				}
				result.getObjectSummaries().stream().map(S3ObjectSummary::getKey).forEach(fileKey->{
					GetObjectRequest getObjectRequest = new GetObjectRequest(cmd.bucket, fileKey);
					File dst = new File(cmd.getDstPath() + "/" + env + File.separator + fileKey);
					dst.getParentFile().mkdirs();
					ObjectMetadata objectMetadata = s3.getObject(getObjectRequest, dst);
					System.out.println("downloading ["+fileKey+"] --> "+dst.getPath());
					System.out.println(objectMetadata.getUserMetadata());
					System.out.println(objectMetadata.getRawMetadata());
				});
			}else{
				System.out.println("not files like '^"+ begin +" exists in "+cmd.getBucket());
			}

			if (isDate(begin)) {
				begin = computeNewDate(begin, 1);
			} else {
				break;
			}
		} while (begin.compareTo(end) <= 0);
	}


	private boolean isDate(String begin) {
		try {
			DateUtils.parseDate(begin, "yyyyMMdd");
		} catch (ParseException e) {
			return false;
		}
		return true;
	}

	private String computeNewDate(String begin, int day) {
		Date date = null;
		try {
			date = DateUtils.parseDate(begin, "yyyyMMdd");
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DAY_OF_YEAR, day);
		return new SimpleDateFormat("yyyyMMdd").format(c.getTime());
	}
}
